package niuke.week3;

import java.util.Scanner;

/**
 给定一个二维数组matrix，可以从任何位置出发，每一步可以走向上、下、左、右，四个方向。返回最大递增链的长度。

 输入
 3 3
 5  4  3
 3  1  2
 2  1  3
 输出
 5
 说明
 1-2-3-4-5

 */
public class MaxChainWithIncrease {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int n = sc.nextInt();
        int m = sc.nextInt();

        int [][]arr = new int[n][m];

        int [][]dp = new int[n][m];//dp_i,j 到达i,j，最长的距离

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        int res=0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                res = Math.max(res,process(arr, i, j, dp));
            }
        }
        System.out.println(res);
    }

    static int  process(int [][] arr, int x, int y,int [][] dp) {
        if (x<0 || y<0 || x>=arr.length||y>=arr[0].length){
            return -1;
        }
        if (dp[x][y] != 0) {//记忆化搜索
            return dp[x][y];
        }
        int next1 = 0;
        int next2 = 0;
        int next3 = 0;
        int next4 = 0;
        if (x - 1 >= 0 && arr[x - 1][y] > arr[x][y]){//向上走
            next1 = process(arr, x - 1, y, dp);
        }
        if (x + 1 < arr.length && arr[x + 1][y] > arr[x][y]) {//下
            next2 = process(arr, x + 1, y, dp);
        }
        if (y - 1 >= 0 && arr[x][y - 1] > arr[x][y]) {//左
            next3 = process(arr, x, y - 1, dp);
        }
        if (y + 1 < arr[0].length && arr[x][y + 1] > arr[x][y]) {//右
            next4 = process(arr, x, y + 1, dp);
        }
        int res = 1 + Math.max(Math.max(next1, next2), Math.max(next3, next4));
        dp[x][y] = res;
        return res;
    }
}